/*
' Copyright (c) 2011  DotNetNuke Corporation
'  All rights reserved.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
'
*/

using System;
using System.Transactions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Modules._2DoTasks.Components;
using DotNetNuke.Modules._2DoTasks.Components.Controllers;
using DotNetNuke.Modules._2DoTasks.Components.Entities;
using DotNetNuke.Modules._2DoTasks.Components.ExceptionHandling;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;

namespace DotNetNuke.Modules._2DoTasks
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The View_2DoTasks class displays the content
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class TaskList : _2DoTasksModuleBase, IActionable
    {
        public const short TaskClosed = (short)SharedEnum.TaskStatus.Closed;
        private const string TaskListCookie = "TaskList";
        private const string FilterAssignedCookieOption = "FilterAssigned";
        private const string FilterAditionalCookieOption = "FilterAditionalOption";

        #region "Properties"

        /// <summary>
        /// Property for the filter assigned option
        /// </summary>
        public SharedEnum.FilterAssigned FilterAssignedOption
        {
            get
            {
                return (SharedEnum.FilterAssigned)Enum.Parse(typeof(SharedEnum.FilterAssigned), drp_assignedOptions.SelectedValue);
            }
        }

        /// <summary>
        /// Property for the filter aditional options
        /// </summary>
        public Nullable<SharedEnum.Task_FilterAditionalOptions> FilterAditionalOptions
        {
            get
            {
                if (drp_filterAditionalOptions.SelectedValue.Equals(string.Empty))
                    return null;
                return (SharedEnum.Task_FilterAditionalOptions)Enum.Parse(typeof(SharedEnum.Task_FilterAditionalOptions), drp_filterAditionalOptions.SelectedValue);
            }
        }

        #endregion "Properties"

        #region Event Handlers

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// -----------------------------------------------------------------------------
        private void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                Messages.ClearMessages();
                if (!Page.IsPostBack)
                {
                    FillControls();

                    if (Task_Created)
                        Messages.ShowSuccess(Localization.GetString("SuccessAddTask", this.LocalResourceFile));
                    else if (Task_Updated)
                        Messages.ShowSuccess(Localization.GetString("SuccessUpdateTask", this.LocalResourceFile));
                    else if (Task_Deleted)
                        Messages.ShowSuccess(Localization.GetString("SuccessDeleteTask", this.LocalResourceFile));
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void lst_tasks_LayoutCreated(object sender, EventArgs e)
        {
            (lst_tasks.FindControl("dv_projectHeader") as Control).Visible = !ProjectId.HasValue;

            (lst_tasks.FindControl("lt_Id") as Literal).Text = Localization.GetString("TitleTaskId", this.LocalResourceFile);
            (lst_tasks.FindControl("lt_Project") as Literal).Text = Localization.GetString("TitleProject", this.LocalResourceFile);
            (lst_tasks.FindControl("lt_Name") as Literal).Text = Localization.GetString("TitleName", this.LocalResourceFile);
            (lst_tasks.FindControl("lt_requester") as Literal).Text = Localization.GetString("TitleRequester", this.LocalResourceFile);
            (lst_tasks.FindControl("lt_AssignedTo") as Literal).Text = Localization.GetString("TitleAssignedTo", this.LocalResourceFile);
            (lst_tasks.FindControl("lt_type") as Literal).Text = Localization.GetString("TitleTaskType", this.LocalResourceFile);
            (lst_tasks.FindControl("lt_status") as Literal).Text = Localization.GetString("TitleTaskStatus", this.LocalResourceFile);
            (lst_tasks.FindControl("lt_targetDate") as Literal).Text = Localization.GetString("TitleTargetDate", this.LocalResourceFile);
        }

        /// <summary>
        /// Databound for listview task control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lst_tasks_ItemDataBound(object sender, System.Web.UI.WebControls.ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                var lnk_edit = e.Item.FindControl("lnk_edit") as LinkButton;
                var lnk_delete = e.Item.FindControl("lnk_delete") as LinkButton;

                var curTask = (_Task)e.Item.DataItem;

                if (IsEditable && lnk_edit != null && lnk_delete != null)
                {
                    lnk_edit.CommandArgument = curTask.TaskId.ToString();
                    lnk_delete.CommandArgument = curTask.TaskId.ToString();

                    string editUrl = EditUrl(String.Empty, string.Empty, "Edit", "tid=" + curTask.TaskId.ToString());
                    if (PortalSettings.EnablePopUps)
                    {
                        lnk_edit.Attributes.Add("onclick", "return " + UrlUtils.PopUpUrl(editUrl, Page, PortalSettings, true, false));
                    }
                    else
                    {
                        lnk_edit.CommandArgument = editUrl;
                    }

                    DotNetNuke.UI.Utilities.ClientAPI.AddButtonConfirm(lnk_delete,
                        Localization.GetString("DeleteConfirm", this.LocalResourceFile).Replace("[TASKID]", curTask.TaskId.ToString()));
                }

                //else
                //    pnlAdminControls.Visible = false;
            }
        }

        /// <summary>
        /// Presents the edit control, for editing the selected task
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkEdit_Click(object sender, EventArgs e)
        {
            Page.Response.Redirect((sender as LinkButton).CommandArgument);
        }

        /// <summary>
        /// Deletes a task
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnk_delete_Click(object sender, EventArgs e)
        {
            try
            {
                int taskId = Convert.ToInt32((sender as LinkButton).CommandArgument);

                using (UnitOfWork uof = new UnitOfWork(PortalId, ModuleId))
                {
                    using (TransactionScope scope = new TransactionScope())
                    {
                        TaskController taskController = new TaskController(uof);
                        taskController.Delete(new _Task { TaskId = taskId });

                        scope.Complete();
                        Response.Redirect(Globals.NavigateURL(string.Empty, string.Empty, "tsk=3"));
                    }
                }
            }
            catch (TaskValidationException exc)
            {
                TaskController.DeleteStatus status =
                    (TaskController.DeleteStatus)Enum.Parse(typeof(TaskController.DeleteStatus), exc.ErrorCode().ToString());

                switch (status)
                {
                    case TaskController.DeleteStatus.CURRENTUSERNOTMEMBER:
                        Messages.ShowWarning(Localization.GetString("WarningCURRENTUSERNOTMEMBER", this.LocalResourceFile));
                        break;

                    case TaskController.DeleteStatus.ONLYCREATORCANDELETE:
                        Messages.ShowWarning(Localization.GetString("WarningONLYCREATORCANDELETE", this.LocalResourceFile));
                        break;

                    default:
                        Exceptions.LogException(exc);
                        Messages.ShowError(Localization.GetString("ErrorDELETETASK", this.LocalResourceFile));
                        break;
                }
            }
            catch (Exception exc)
            {
                this.Messages.ShowError(Localization.GetString("ErrorDELETETASK", this.LocalResourceFile));

                Exceptions.LogException(exc);
            }
        }

        /// <summary>
        /// Redo the search for tasks based on the user search
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void drp_filterChange_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //save options to cookie
                HttpCookie tskListCookie = new HttpCookie(TaskListCookie);
                tskListCookie.Values[FilterAssignedCookieOption] = drp_assignedOptions.SelectedValue;
                tskListCookie.Values[FilterAditionalCookieOption] = drp_filterAditionalOptions.SelectedValue;
                tskListCookie.Expires = DateTime.Now.AddDays(1);
                Response.Cookies.Add(tskListCookie);
                using (UnitOfWork uof = new UnitOfWork(PortalId, ModuleId))
                {
                    BindTasks(uof);
                }
            }
            catch (Exception exc)
            {
                this.Messages.ShowError(Localization.GetString("ErrorBindTASKs", this.LocalResourceFile));

                Exceptions.LogException(exc);
            }
        }

        #endregion Event Handlers

        #region "Aux Functions"

        /// <summary>
        /// Fills module controls
        /// </summary>
        private void FillControls()
        {
            //get cookie
            HttpCookie tslCookie = Request.Cookies[TaskListCookie];

            FillTaskOwnerOptions(tslCookie);
            FillAditionalOptions(tslCookie);

            using (UnitOfWork uof = new UnitOfWork(PortalId, ModuleId))
            {
                BindTasks(uof);

                //Set Title
                SetTitle(uof);
            }
        }

        /// <summary>
        /// Set the title for the list
        /// </summary>
        private void SetTitle(UnitOfWork uof)
        {
            //if project has value
            if (ProjectId.HasValue)
            {
                //  get the project and present the title has project tasks
                ProjectController prjController = new ProjectController(uof);
                var project = prjController.Get(ProjectId.Value);
                lt_tasksTitle.Text = Localization.GetString("ProjectTasksTitle", this.LocalResourceFile).Replace("[PROJECTNAME]", project.Name);
            }
            else
            {
                //  else set has existing tasks
                lt_tasksTitle.Text = Localization.GetString("TasksTitle", this.LocalResourceFile);
            }
        }

        /// <summary>
        /// Binds the available tasks, into the respective control
        /// </summary>
        private void BindTasks(UnitOfWork uof)
        {
            //fill existing tasks

            TaskController taskController = new TaskController(uof);

            var tasks = taskController.Find(FilterAssignedOption, FilterAditionalOptions, ProjectId);
            lst_tasks.DataSource = tasks;
            lst_tasks.DataBind();
        }

        /// <summary>
        /// Fills the assigned options control
        /// </summary>
        /// <param name="tslCookie">cookie with last data used for listing tasks</param>
        private void FillTaskOwnerOptions(HttpCookie tslCookie)
        {
            Array enumValues = System.Enum.GetValues(typeof(SharedEnum.FilterAssigned));

            foreach (SharedEnum.FilterAssigned option in enumValues)
            {
                drp_assignedOptions.Items.Add(
                    new ListItem(Localization.GetString(option.ToString(), this.LocalResourceFile),
                                    ((int)option).ToString()));
            }

            //get last value saved for FilterAssigned
            string lastSavedFilterAssignedOption;
            if (tslCookie != null && (lastSavedFilterAssignedOption = tslCookie[FilterAssignedCookieOption]) != null)
            {
                var item = drp_assignedOptions.Items.FindByValue(lastSavedFilterAssignedOption);
                if (item != null)
                    item.Selected = true;
            }
        }

        /// <summary>
        /// Fills the other filter options control
        /// </summary>
        /// <param name="tslCookie">cookie with last data used for listing tasks</param>
        private void FillAditionalOptions(HttpCookie tslCookie)
        {
            Array enumValues = System.Enum.GetValues(typeof(SharedEnum.Task_FilterAditionalOptions));

            foreach (SharedEnum.Task_FilterAditionalOptions option in enumValues)
            {
                drp_filterAditionalOptions.Items.Add(
                    new ListItem(Localization.GetString(option.ToString(), this.LocalResourceFile),
                                    ((int)option).ToString()));
            }
            drp_filterAditionalOptions.Items.Add(
                    new ListItem(Localization.GetString("All", this.LocalResourceFile), string.Empty));

            //get last value saved for FilterAditionalOption
            string lastSavedFilterAditionalOption;
            if (tslCookie != null && (lastSavedFilterAditionalOption = tslCookie[FilterAditionalCookieOption]) != null)
            {
                var item = drp_filterAditionalOptions.Items.FindByValue(lastSavedFilterAditionalOption);
                if (item != null)
                    item.Selected = true;
            }
        }

        /// <summary>
        /// Returns the string representative of the task type
        /// </summary>
        /// <returns></returns>
        public string GetTaskType(Int16 typeId)
        {
            return Localization.GetString(((SharedEnum.TaskType)Enum.Parse(typeof(SharedEnum.TaskType), typeId.ToString())).ToString(), this.LocalResourceFile);
        }

        /// <summary>
        /// Returns the string representative of the task status
        /// </summary>
        /// <returns></returns>
        public string GetTaskStatus(Int16 statusId)
        {
            return Localization.GetString(((SharedEnum.TaskStatus)Enum.Parse(typeof(SharedEnum.TaskStatus), statusId.ToString())).ToString(), this.LocalResourceFile);
        }

        #endregion "Aux Functions"

        #region Optional Interfaces

        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(GetNextActionID(), Localization.GetString("EditModule", this.LocalResourceFile), "", "", "", EditUrl(), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }

        #endregion Optional Interfaces
    }
}